'use strict';

const BaseController = require('./base');

class LogisticsTrackController extends BaseController {
  constructor(ctx) {
    super(ctx, 'logisticsTrack');
  }

  getPageInclude() {
    return [
      { model: this.ctx.model.ExpressOrder, as: 'order', include: [
        { model: this.ctx.model.LogisticsCompany, as: 'logisticsCompany' }
      ]}
    ];
  }

  getListInclude() {
    return [
      { model: this.ctx.model.ExpressOrder, as: 'order' }
    ];
  }

  getDetailInclude() {
    return [
      { model: this.ctx.model.ExpressOrder, as: 'order', include: [
        { model: this.ctx.model.LogisticsCompany, as: 'logisticsCompany' }
      ]}
    ];
  }

  // 添加物流轨迹
  async addTrack() {
    const { ctx } = this;
    const data = ctx.request.body;
    
    if (!data.order_id) ctx.throw(400, '订单ID不能为空');
    if (!data.track_info) ctx.throw(400, '轨迹信息不能为空');
    
    // 设置操作人
    if (!data.operator && ctx.session.user) {
      data.operator = ctx.session.user.nickname;
    }
    
    const track = await ctx.service.logisticsTrack.create(data);
    
    // 如果有设置订单状态，同时更新订单状态
    if (data.order_status !== undefined) {
      await ctx.service.expressOrder.update(data.order_id, {
        order_status: data.order_status
      });
    }
    
    ctx.success(track, 200);
  }
}

module.exports = LogisticsTrackController;
